﻿using System;
using System.Collections;
using System.Drawing;
using System.Data.SqlServerCe;
using System.Data;
using System.Windows.Forms;

namespace EffortsTracker
{
    public class Session
    {
        public int id;
        //public string name;
        public double totalTimeSpent;
        public int numKeys = 0;
        public int numMouseClicks = 0;
        public DateTime initialStartDate;
        public DateTime finalFinishDate;
        public SessionStatus sessionStatus = SessionStatus.STOPPED;
        public Project project;

        ArrayList mouseClicks = new ArrayList();
        ArrayList keyboardEvents = new ArrayList();
        ArrayList screenShots = new ArrayList();

        public Session(Project project)
        {
            this.project = project;
        }
        public Session(int id)
        {
            this.id = id;
        }
        public Session(int id, /*string name,*/ double totalTimeSpent, DateTime initialStartDate, DateTime finalFinishDate, SessionStatus sessionStatus, Project project)
        {
            this.id = id;
            //this.name = name;
            this.totalTimeSpent = totalTimeSpent;
            this.initialStartDate = initialStartDate;
            this.finalFinishDate = finalFinishDate;
            this.sessionStatus = sessionStatus;
            this.project = project;
        }
        
        public void getDetails()
        {
        }

        public void save()
        {
            finalFinishDate = DateTime.Now;
            saveMouseClicks(mouseClicks);
            mouseClicks.Clear();
            saveKeyboardEvents(keyboardEvents);
            keyboardEvents.Clear();
            if (id > 0)
                update();
            else
                add();
        }

        public void export()
        {
        }

        public void add()
        {
            SqlCeConnection sqlConnection = Database.getConnection();
            SqlCeCommand command = sqlConnection.CreateCommand();
            command.CommandText = "insert into sessions (initial_start_date, final_end_date, current_status, project_id) values ('" + initialStartDate.ToString(Database.dateFormat) + "', '" + finalFinishDate.ToString(Database.dateFormat) + "', " + (int)sessionStatus + ", " + project.id + ")";
            command.ExecuteNonQuery();
            command.CommandText = "SELECT @@IDENTITY";
            SqlCeDataReader sqlDataReader = command.ExecuteReader();
            if (sqlDataReader.Read())
            {
                this.id = (int)sqlDataReader.GetDecimal(0);
            }
            sqlDataReader.Close();
            sqlConnection.Close();
        }
        public void update()
        {
            SqlCeConnection sqlConnection = Database.getConnection();
            SqlCeCommand command = sqlConnection.CreateCommand();
            command.CommandText = "update sessions set final_end_date='" + finalFinishDate.ToString(Database.dateFormat) + "', current_status=" + (int)sessionStatus + " where id=" + id;
            command.ExecuteNonQuery();
            sqlConnection.Close();
        }
        public void delete()
        {
            SqlCeConnection sqlConnection = Database.getConnection();
            SqlCeCommand command = sqlConnection.CreateCommand();
            command.CommandText = "delete from mouse_clicks where session_id=" + this.id;
            command.ExecuteNonQuery();
            command.CommandText = "delete from keyboard_events where session_id=" + this.id;
            command.ExecuteNonQuery();
            command.CommandText = "delete from screen_shots where session_id=" + this.id;
            command.ExecuteNonQuery();
            command.CommandText = "delete from sessions where id=" + this.id;
            command.ExecuteNonQuery();
            sqlConnection.Close();
        }

        public void addMouseClick(DateTime date)
        {
            mouseClicks.Add(date);
            if (mouseClicks.Count > 100)
            {
                ArrayList tempMouseClicks = (ArrayList)mouseClicks.Clone();
                mouseClicks.Clear();
                saveMouseClicks(tempMouseClicks);
            }
        }

        private void saveMouseClicks(ArrayList tempMouseClicks)
        {
            SqlCeConnection sqlConnection = Database.getConnection();
            SqlCeCommand command = sqlConnection.CreateCommand();
            for (int i = 0; i < tempMouseClicks.Count; i++)
            {
                command.CommandText = "insert into mouse_clicks (session_id, date) values (" + this.id + ", '" + ((DateTime)tempMouseClicks[i]).ToString(Database.dateFormat) + "')";
                command.ExecuteNonQuery();
            }
            sqlConnection.Close();
        }

        public void addKeyboardEvent(DateTime date)
        {
            keyboardEvents.Add(date);
            if (keyboardEvents.Count > 100)
            {
                ArrayList tempKeyboardEvents = (ArrayList)keyboardEvents.Clone();
                keyboardEvents.Clear();
                saveKeyboardEvents(tempKeyboardEvents);
            }
        }

        private void saveKeyboardEvents(ArrayList tempKeyboardEvents)
        {
            SqlCeConnection sqlConnection = Database.getConnection();
            SqlCeCommand command = sqlConnection.CreateCommand();
            for (int i = 0; i < tempKeyboardEvents.Count; i++)
            {
                command.CommandText = "insert into keyboard_events (session_id, date) values (" + this.id + ", '" + ((DateTime)tempKeyboardEvents[i]).ToString(Database.dateFormat) + "')";
                command.ExecuteNonQuery();
            }
            sqlConnection.Close();
        }

        public void addScreenShot(ScreenShot screenShot)
        {
            //screenShots.Add(screenShot);
            SqlCeConnection sqlConnection = Database.getConnection();
            SqlCeCommand command = sqlConnection.CreateCommand();
            byte[] photo = screenShot.getImageAsByteArray();
            command.CommandText = "insert into screen_shots (session_id, screen_shot, date) values (" + this.id + ", @Photo, '" + screenShot.date.ToString(Database.dateFormat) + "')"; 
            command.Parameters.Add("@Photo", SqlDbType.Image, photo.Length).Value = photo;
            command.ExecuteNonQuery();
            sqlConnection.Close();
        }

        public static Session[] getAllSessions()
        {
            ArrayList sessions = new ArrayList();
            SqlCeConnection sqlConnection = Database.getConnection();
            SqlCeCommand command = sqlConnection.CreateCommand();
            command.CommandText = "Select id, initial_start_date, final_end_date, current_status, project_id from sessions";
            SqlCeDataReader sqlDataReader = command.ExecuteReader();
            while (sqlDataReader.Read())
            {
                Session session = new Session(sqlDataReader.GetInt32(0)// ID
                    //, sqlDataReader.GetString(1) // Name
                    , sqlDataReader.GetDateTime(2).Subtract(sqlDataReader.GetDateTime(1)).TotalSeconds // Total Spent Time
                    , sqlDataReader.GetDateTime(1) // Initial start date
                    , sqlDataReader.GetDateTime(2) // Final End date
                    , (SessionStatus)sqlDataReader.GetInt32(3) // current status
                    , Project.getProject(sqlDataReader.GetInt32(4))); // Project
                
                sessions.Add(session);
            }
            sqlDataReader.Close();
            sqlConnection.Close();
            return (Session[])sessions.ToArray(typeof(Session));
        }

        public static Session getSession(int id)
        {
            Session session = null;
            SqlCeConnection sqlConnection = Database.getConnection();
            SqlCeCommand command = sqlConnection.CreateCommand();
            command.CommandText = "Select id, total_spent_time, initial_start_date, final_end_date, current_status, project_id from sessions where id=" + id;
            SqlCeDataReader sqlDataReader = command.ExecuteReader();
            if (sqlDataReader.Read())
            {
                session = new Session(sqlDataReader.GetInt32(0)// ID
                    //, sqlDataReader.GetString(1) // Name
                    , sqlDataReader.GetDateTime(2).Subtract(sqlDataReader.GetDateTime(1)).TotalSeconds // Total Spent Time
                    , sqlDataReader.GetDateTime(1) // Initial start date
                    , sqlDataReader.GetDateTime(2) // Final End date
                    , (SessionStatus)sqlDataReader.GetInt32(3) // current status
                    , Project.getProject(sqlDataReader.GetInt32(4)));
            }
            sqlDataReader.Close();
            sqlConnection.Close();
            return session;
        }
    }
}